package com.stephen.redisdemo.atomic;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.TimeUnit;

/**
 * @author: stephen
 * @create: 2020-02-29 14:01
 * @description: 循环屏障
 *  cyclicBarrier.await(); 所有线程在此等待,全部执行到此处后,执行runnable中的代码
 *  然后,再执行await()之后的代码
 */
public class CyclicBarrierDemo {

    public static void main(String[] args) {
        CyclicBarrier cyclicBarrier = new CyclicBarrier(7,()-> {
            System.out.println("---------召唤神龙--------");
        });

        for (int i = 0; i < 7; i++) {
            new Thread(() -> {
                System.out.println(Thread.currentThread().getName()+ "\t" + "找龙珠开始");
                try {
                    TimeUnit.SECONDS.sleep(2);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                try {
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread().getName()+ "\t" + "找龙珠结束");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }
    }
}
